package jsyf.oa.service.salary;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jsyf.com.util.DateUtils;
import jsyf.com.util.FastJsonConvert;
import jsyf.oa.dao.salary.SalaryDetailsDao;
import jsyf.oa.dao.wechat.service_company.TokenDao;
import jsyf.oa.entity.salary.SalaryDetailsEntity;
import jsyf.oa.entity.salary.SalaryMainEntity;
import jsyf.oa.facade.salary.SalaryDetailsFacade;
import jsyf.oa.service.wechat.service_company.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Maqiuqiu on 2018/11/19.
 */
@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class SalaryDetailsService implements SalaryDetailsFacade {
    @Value("${oa.URLConfig}")
    private String urlConfig;
    @Autowired
    private SalaryDetailsDao salaryDetailsDao;
    @Autowired
    private TokenDao tokenDao;
    //给内部人员发工资条
    public static final String SENDER_INNER_REMIND = "%1s，你好！\n" +
            "%2s月工资已发放，\n" +
            "实发工资%3s。 <a href='%4s'>点此查看详情</a>";
    NumberFormat format = NumberFormat.getCurrencyInstance(Locale.CHINA);

    @Override
    public String save(String jsonData) {
        SalaryDetailsEntity entity = JSON.toJavaObject(JSON.parseObject(jsonData), SalaryDetailsEntity.class);
        Integer rows;
        if ("0".equals(entity.getId()) || StringUtils.isBlank(entity.getId())) {
            rows = salaryDetailsDao.add(entity);
        } else {
            SalaryDetailsEntity salaryDetailsEntity = (SalaryDetailsEntity) salaryDetailsDao.getIBaseEntityById(entity.getId());
            salaryDetailsEntity.setSalaryId(entity.getSalaryId());
            salaryDetailsEntity.setUserId(entity.getUserId());
            salaryDetailsEntity.setPreSalaryStandard(entity.getPreSalaryStandard());
            salaryDetailsEntity.setCurSalaryStandard(entity.getCurSalaryStandard());
            salaryDetailsEntity.setOvertimeDays(entity.getOvertimeDays());
            salaryDetailsEntity.setWages(entity.getWages());
            salaryDetailsEntity.setFoodAllowance(entity.getFoodAllowance());
            salaryDetailsEntity.setCarSupplementStandard(entity.getCarSupplementStandard());
            salaryDetailsEntity.setCarSupplement(entity.getCarSupplement());
            salaryDetailsEntity.setCallSupplement(entity.getCallSupplement());
            salaryDetailsEntity.setHouseSupplement(entity.getHouseSupplement());
            salaryDetailsEntity.setOtherSupplement(entity.getOtherSupplement());
            salaryDetailsEntity.setPersonnelDeduction(entity.getPersonnelDeduction());
            salaryDetailsEntity.setOtherDetuction(entity.getOtherDetuction());
            salaryDetailsEntity.setPayable(entity.getPayable());
            salaryDetailsEntity.setInsuranceGold(entity.getInsuranceGold());
            salaryDetailsEntity.setTaxAmount(entity.getTaxAmount());
            salaryDetailsEntity.setShouldTax(entity.getShouldTax());
            salaryDetailsEntity.setRepayment(entity.getRepayment());
            salaryDetailsEntity.setRealPay(entity.getRealPay());
            salaryDetailsEntity.setRemark(entity.getRemark());
            salaryDetailsEntity.setPayDate(entity.getPayDate());
            salaryDetailsEntity.setRyNo(entity.getRyNo());
            salaryDetailsEntity.setDepartId(entity.getDepartId());
            salaryDetailsEntity.setDepartName(entity.getDepartName());
            salaryDetailsEntity.setUserName(entity.getUserName());
            salaryDetailsEntity.setRoleName(entity.getRoleName());
            salaryDetailsEntity.setEntryDate(entity.getEntryDate());
            salaryDetailsEntity.setWegeCard(entity.getWegeCard());
            salaryDetailsEntity.setProvince(entity.getProvince());
            salaryDetailsEntity.setCity(entity.getCity());
            salaryDetailsEntity.setCountry(entity.getCountry());
            salaryDetailsEntity.setBank(entity.getBank());
            salaryDetailsEntity.setCard(entity.getCard());
            salaryDetailsEntity.setShouldSignIn(entity.getShouldSignIn());
            salaryDetailsEntity.setRealSignIn(entity.getRealSignIn());
            salaryDetailsEntity.setLeaveDays(entity.getLeaveDays());
            salaryDetailsEntity.setSignInStandard(entity.getSignInStandard());
            salaryDetailsEntity.setSignInFormer(entity.getSignInFormer());
            rows = salaryDetailsDao.update(salaryDetailsEntity);
        }
        return rows == 0 ? "" : entity.getId();
    }

    @Override
    public Boolean delById(String jsonData) {
        return salaryDetailsDao.delById(JSON.parseObject(jsonData).getString("id")) > 0;
    }

    @Override
    public List<JSONObject> getSalaryList(String jsonObject) {
        JSONObject JSONObject = JSON.parseObject(jsonObject);
        String sampleId = JSONObject.getString("salaryId");
        return salaryDetailsDao.getJSONListByCondition("AND SALARY_ID=?", new Object[]{sampleId});

    }

    @Override
    public JSONObject getSalaryById(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        JSONObject salaryInfo = this.salaryDetailsDao.getJSONById(jsonParams.getString("id"));
        return salaryInfo;
    }

    @Override
    public JSONObject getSalaryByUserIdAndMonth(String jsonData) {
        JSONObject JSONObject = JSON.parseObject(jsonData);
        String userId = JSONObject.getString("userId");
        String month = JSONObject.getString("month");
        JSONObject returnData = new JSONObject();
        List<JSONObject> salaryInfo = this.salaryDetailsDao.getJSONListByCondition("AND USER_ID=? AND MONTH=?", new Object[]{userId, month});
        if (salaryInfo != null && salaryInfo.size() > 0) {
            returnData = salaryInfo.get(0);
        }
        return returnData;

    }

    @Override
    public Boolean senderSalary(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String attachName = jsonParams.getString("attachName");
        String month = "";
        if (StringUtils.isNotEmpty(attachName)) {
            String regex = "\\d{4}年\\d{1,2}";
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(attachName);
            if (matcher.find()) {
                month = matcher.group(0).replace("年", "-");
            }
        }
        List<JSONObject> salaryList = salaryDetailsDao.getJSONListByCondition(" and ATTACH_NAME=? and MONTH=?", new Object[]{attachName, month});
        if (salaryList != null && salaryList.size() > 0) {
            for (int i = 0; i < salaryList.size(); i++) {
                JSONObject salary = salaryList.get(i);
                String userId = salary.getString("userId");
                String userName = salary.getString("userName");
                String realPay = salary.getString("realPay");
                String money = formateRate(realPay);
                String realMoney = format.format(Double.parseDouble(money));
                String httpHtml = urlConfig + "/salary/detailApp.html?userId=" + userId + "&month=" + month + "";
                JSONObject msgObject = new JSONObject();
                msgObject.put("userIds", userId);
                msgObject.put("content", String.format(SENDER_INNER_REMIND, userName, month, realMoney, httpHtml));
                tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
            }
        }
        return true;
    }

    public String formateRate(String rateStr) {
        if (rateStr.indexOf(".") != -1) {
            //获取小数点的位置
            int num = 0;
            num = rateStr.indexOf(".");

            //获取小数点后面的数字 是否有两位 不足两位补足两位
            String dianAfter = rateStr.substring(0, num + 1);
            String afterData = rateStr.replace(dianAfter, "");
            if (afterData.length() < 2) {
                afterData = afterData + "0";
            } else {
                afterData = afterData;
            }
            return rateStr.substring(0, num) + "." + afterData.substring(0, 2);
        } else {
            if (rateStr == "1") {
                return "100";
            } else {
                return rateStr;
            }
        }
    }
}
